package com.terra.ns.imp.common.dingtalk.service

import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest
import com.aliyun.tea.TeaException
import com.terra.ns.imp.common.dingtalk.client.DingtalkClient
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
@author qins
@date 2023/9/20
@desc 钉钉授权信息
 */
class DingAuthService {


    private val log = LoggerFactory.getLogger(this::class.java)
    /**
     * 缓存时间：100分钟; 钉钉的token为120分支
     */
    private val cacheTtl = 100 * 60 * 1000L

    private var accessTokenTimeOut = 0L

    @Autowired
    private lateinit var dingtalkClient: DingtalkClient

    /**
     * 企业内部应用accessToken
     */
    private var accessToken: String = ""


    fun getAccessToken() : String {
        val now = System.currentTimeMillis()
        if(accessToken.isNotBlank() && now < accessTokenTimeOut) {
            return accessToken
        }
        val request = GetAccessTokenRequest()
            .setAppKey(dingtalkClient.getDingtalkConf().appKey)
            .setAppSecret(dingtalkClient.getDingtalkConf().appSecret)
        try {
            val accessTokenResult = dingtalkClient.authClient().getAccessToken(request).body
            this.accessTokenTimeOut = now + cacheTtl
            this.accessToken = accessTokenResult.accessToken
            return accessToken
        } catch (err: TeaException) {
            log.error("获取accessToken失败：{}", err.message)
            throw RuntimeException(err.message)
        }
    }

}